
const express = require('express');
const md5 = require("md5")
const usersSchema = require("../database/controlUser")
const database = require("../database/connectDataBase")
const jwt = require("jsonwebtoken") // 生成用户令牌以及登录校验
const { validationResult, body } = require('express-validator');  // 进行数据校验
const { userrules, userNamerules,updateUserinforules } = require('../utils/validators')  // 导入校验规则
const jwtverify = require("../utils/jwtverify")  //用户登录校验

const { Secret_key, Token_Time } = require('../config')  // 导入相关配置


const router = express.Router();

database(() => {
  /* POST users register. */
  router.post('/register', userrules,
    (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(200).json({ errorCode: 400, msg: "数据校验失败", data: null, errors: errors.array() });
      }
      req.body.userPassword = md5(req.body.userPassword)
      usersSchema.create(req.body).then(() => {
        res.json({
          errorCode: 0,
          msg: "注册成功",
          data: req.body.userName,
          errors: null
        })
      }).catch((err) => {
        res.json({
          errorCode: 400,
          msg: "注册失败",
          data: null,
          errors: err
        })
      })
    })

  // 用户登录接口
  router.post('/login', userrules,
    (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(200).json({ errorCode: 400, msg: "数据校验失败", data: null, errors: errors.array() });
      }

      usersSchema.findOne(
        { userName: req.body.userName, userPassword: req.body.userPassword },
        { userName: 1, avatar: 1, _id: 1 }
        ).then((result) => {
        // 如果检测到用户不存在
        if (!result) return res.json({ errorCode: 400, msg: "用户名或密码错误", data: null, errors: null })

        // 用户存在逻辑
        const userName = req.body.userName
        const token = jwt.sign({ userName }, Secret_key, { expiresIn: Token_Time })  // 生成用户令牌
        res.json({
          errorCode: 0,
          msg: "登录成功",
          data: {
            result,
            token
          },
          errors: null
        })

      }).catch((err) => {
        res.json({
          errorCode: 400,
          msg: "注册失败",
          data: null,
          errors: err
        })
      })
    }
  )

  // 检测用户登录状态
  router.get('/status', jwtverify, (req, res) => {
    res.json({
      errorCode: 0,
      msg: "已经登录",
      data: null,
      errors: null
    })
  })

  // 获取用户信息
  router.get("/userinfo", jwtverify, userNamerules, async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(200).json({ errorCode: 400, msg: "数据校验失败", data: null, errors: errors.array() });
    }
    try {
      const userinfo = await usersSchema.findOne(
        { userName: req.query.userName},
        { userName: 1, avatar: 1, _id: 0 }
      )
      return res.status(200).json({
        errorCode: 0,
        msg: "查询成功",
        data: userinfo,
        errors: null
      });
    } catch (err) {
      console.error('Error creating link:', err);
      return res.status(200).json({
        errorCode: 400,
        msg: "查询失败",
        data: null,
        errors: err.message
      });
    }
  })

  // 修改用户信息
  router.put("/userinfo",jwtverify,updateUserinforules, async (req,res)=>{
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(200).json({ errorCode: 400, msg: "数据校验失败", data: null, errors: errors.array() });
    }

    const {userName,avatar,_id} = req.body
    try{
      const updateResult = await usersSchema.findByIdAndUpdate(_id,{
        userName,
        avatar
      })
      res.json({
        errorCode: 0,
        msg: "更新成功",
        data: {userName,avatar,_id},
        errors: null
      })
    }catch(err){
      res.json({
        errorCode: 400,
        msg: "修改失败",
        data: null,
        errors: err
      })
    }

  })

}, () => { })

module.exports = router;
